package com.ch.dream.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

public class MyDatabase extends SQLiteOpenHelper {

	private static String DBName = "ms";
	public static String shortStoryCollect ="shortStoryCollect";
	private static final int VERSION = 1;
	private static SQLiteDatabase mDb = null;
	private Context mContext;
	public MyDatabase(Context context) {
		super(context, DBName, null, VERSION);
		mContext = context;
		if(mDb==null || !mDb.isOpen())
			mDb = getWritableDatabase();
	}

	public void clear(){
		mContext.deleteDatabase(DBName);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table if not exists "+shortStoryCollect+"("
				+ "_id INTEGER primary key,"
				+ "storyId varchar,"
				+ "content varchar,"
				+ "createTime varchar)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("drop table if exists "+shortStoryCollect);
		onCreate(db);
	}

	public long insert(String tabName, ContentValues values) {
		long rowId = -1;
		if (tabName.length() > 0)
			rowId = mDb.insert(tabName, "_id", values);
		return rowId;
	}

	public int delete(String tabName, String where, String[] whereArgs) {
		int count = 0;
		try {
			count = mDb.delete(tabName, where, whereArgs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public Cursor query(String tableName, String[] columns, String selection, String[] selectionArgs,
			String sortOrder) {
		if (tableName.length() == 0 || columns.length == 0)
			return null;

		String orderBy = "";
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = null;
		} else {
			orderBy = sortOrder;
		}
		Cursor c = null;
		try {
			c = mDb.query(tableName, columns, selection, selectionArgs, null, null, orderBy, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public void close() {
		try {
			mDb.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
